package com.bilibili.service;

import com.bilibili.constant.UserConstant;
import com.bilibili.dao.UserDao;
import com.bilibili.dao.UserInfoDao;
import com.bilibili.domain.User;
import com.bilibili.domain.UserInfo;
import com.bilibili.exception.ConditionException;
import com.bilibili.util.MD5Util;
import com.bilibili.util.RSAUtil;
import com.mysql.cj.util.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
public class UserService {
    @Resource
    private UserDao userDao;

    @Resource
    private UserInfoDao userInfoDao;

    public void addUser(User user){
        String phone = user.getPhone();
        if (StringUtils.isNullOrEmpty(phone)){
            throw new ConditionException("手机号不能为空！");
        }
        User dbUser = this.getUserByPhone(phone);
        if (dbUser != null){
            throw new ConditionException("该手机号已经注册！");
        }
        Date date = new Date();
        String salt = String.valueOf(date.getTime());
        String userPassword = user.getUserPassword();
        String rawPassword;
        try {
            rawPassword = RSAUtil.decrypt(userPassword);
        }catch (Exception e){
            throw new ConditionException("密码解密失败");
        }
        String md5Password = MD5Util.sign(rawPassword,salt,"UTF-8");
        user.setSalt(salt);
        user.setUserPassword(md5Password);
        user.setCreateTime(date);
        userDao.addUser(user);
        // 添加用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setNick(UserConstant.DEFAULT_NICK);
        userInfo.setBirth(UserConstant.DEFAULT_BIRTH);
        userInfo.setGender(UserConstant.GENDER_MALE);
        userInfo.setCreateTime(date);
        userInfoDao.addUserInfo(userInfo);
    }

    public User getUserByPhone(String phone){
        return userDao.getUserByPhone(phone);
    }

    public User getUserById(Long id){
        return userDao.getUserById(id);
    }

    public List<UserInfo> getUserInfoByUserIds(Set<Long> userIdList) {
        return userInfoDao.getUserInfoByUserIds(userIdList);
    }
}
